import { Component, Vue } from "vue-property-decorator";
import request from "@/request";
import moment from "moment";
import { Form } from "view-design";

interface Search {
	status:number | null,
	createTimeRange:Date[] | null,
	search:string,
	template:number | null
}

@Component
export default class TableCommon extends Vue {
	dataSource:any[] = [];
	tableLoading:boolean = false;
	form:Search = {
		status: null,
		createTimeRange: null,
		search: "",
		template: null
	};
	page:number = 1;
	total:number = 1;
	template:{ name:string, id:number }[] = [];

	get height ():number {
		return document.body.clientHeight - 274;
	}

	get pageSize ():number {
		return Math.floor((this.height - 36) / 40);
	}

	readonly type:number = 0;

	getEvent (page:number = 1) {
		const type = this.type;
		this.tableLoading = true;
		this.page = page;
		request({
			url: "/repair/rest/projectevent/",
			params: {
				eventtype: type,
				page,
				pagesize: this.pageSize,
				status: this.form.status,
				createtime__range: ((timeRange:Date[] | null):string | null => {
					if (timeRange && timeRange[ 0 ]) {
						return [ moment(timeRange[ 0 ]).format("YYYY-MM-DDT00:00:00"), moment(timeRange[ 1 ]).format("YYYY-MM-DDT23:59:59") ].join();
					} else {
						return null;
					}
				})(this.form.createTimeRange),
				sensorwarn__isnull: true,
				ordering: "status,-createtime",
				floor: this.$store.state.floorValue,
				template: this.form.template
			}
		}).then(({ data }) => {
			this.tableLoading = false;
			this.total = data.count;
			this.dataSource = data.results.map((t:any) => ({
				facility: t.facility_name,
				name: t.describe,
				start: t.createtime.replace(/T.+/, ""),
				related: (<string[]>t.fzr).join(" ") + " " + (t.pjr || ""),
				id: <number>t.id,
				actionable: <boolean>t.isactor,
				loading: <boolean>t.isdoing,
				status: t.status,
				guIdList: ((list:any[]) => {
					if (list && list.length > 0) {
						const temp = JSON.stringify(list);
						const results = temp.match(/{"roomguid":.+?}/);
						if (results) {
							return { roomguid: JSON.parse(results[ 0 ]).roomguid };
						} else {
							return null;
						}
					} else {
						return null;
					}
				})(t.dbidlist)
			}));
		});
	}

	rest () {
		(this.$refs.search as Form).resetFields();
		this.getEvent(1);
	}

	mounted () {
		request({
			url: "/repair/rest/flowtemplate/",
			params: {
				flowtype: 3 - this.type
			}
		}).then(({ data }) => {
			this.template = data.map((t:any) => ({
				name: t.name.replace(/班组/, ""),
				id: t.id
			}));
		});
	}
}
